package chapter.seventh.item43;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import chapter.fifth.item27.GenericUtil;
import chapter.fourth.item17.Sub;
import chapter.fourth.item17.Super;

public class ZeroLenCollection {
	
	@SuppressWarnings("rawtypes")
	private final List subList;
	
	@Override
	public String toString() {
		return subList.toString();
	}
	
	

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((subList == null) ? 0 : subList.hashCode());
		return result;
	}



	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ZeroLenCollection other = (ZeroLenCollection) obj;
		if (subList == null) {
			if (other.subList != null)
				return false;
		} else if (!subList.equals(other.subList))
			return false;
		return true;
	}



	@SuppressWarnings("unchecked")
	private ZeroLenCollection(MineBuilder builder){
		subList = GenericUtil.newArrayList();
		subList.addAll(builder.subList);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public List<? super Super> getSubList(){
		return new ArrayList(subList);
	}
	
	private static class MineBuilder{
		
		@SuppressWarnings("rawtypes")
		private List subList;
		
		public MineBuilder() {
			//this.subList = GenericUtil.newArrayList();
		}

		private ZeroLenCollection build(){
			return new ZeroLenCollection(this);
		}

		@SuppressWarnings("unchecked")
		public MineBuilder setSubList(List<? extends Super> subList) {
			if(subList==null){
				this.subList = Collections.emptyList();
				return this;
			}
			this.subList = GenericUtil.newArrayList();
			this.subList.addAll(subList);
			return this;
		}
		
	}
	
	/**
	 * @Test1  返回零长度的数组
	 * @Test2 builder模式
	 * @Test3   通配符类型
	 * @Test4 equals,hashCode,toString重写
	 * @param args
	 */
	public static void main(String[] args) {
		List<Super> zeroLenList = new ArrayList<Super>();
		zeroLenList.add(new Super());
		zeroLenList.add(new Sub());
		zeroLenList.add(new Super());
		MineBuilder builder  = new ZeroLenCollection.MineBuilder()
				.setSubList(zeroLenList);
		 ZeroLenCollection zlc = builder.build();
		@SuppressWarnings("unchecked")
		List<Object> x = (List<Object>) zlc.getSubList();
		System.out.println(x);
		x.add("x");
		System.out.println(x);
		for(Object o:x){
			System.out.println(o.getClass());
		}
		System.out.println("test create amulti object");
		ZeroLenCollection zero = builder.build();
		System.out.println(zero);
		System.out.println(zero.equals(zlc));
		
	}
}
